#include "CTimer.h"

CTimer* CTimer::m_pTimer = NULL;

CTimer::CTimer()
{
	//Check if hardware support the Performance counter
	if(QueryPerformanceFrequency( &m_NS_Frequency ))
	{
		m_IsPerfHardware	= true;
		QueryPerformanceCounter( &m_NS_LastTime );
		QueryPerformanceCounter( &m_NS_CurrentTime );
	}
	else //if not support us timegettime
	{
		m_IsPerfHardware	= false;
		m_MS_LastTime		= timeGetTime();
		m_MS_CurrentTime	= timeGetTime();
	}
	m_LastFPSTime	= timeGetTime();
	m_Count			= 0;
	m_FPSAvarage	= 0;
}

CTimer::~CTimer()
{
	
}

//---------------------------------//
// Name : GetInstance              //
// Desc : Get an instance of timer //
//---------------------------------//
CTimer* CTimer::GetInstance()
{
	if( m_pTimer == NULL )
	{
		m_pTimer = new CTimer();
	}

	return m_pTimer;
}

//----------------------------//
// Name : Start               //
// Desc : Start to count time //
//----------------------------//
void CTimer::Start()
{
	if(m_IsPerfHardware)
	{
		QueryPerformanceCounter( &m_NS_LastTime );
	}
	else
	{
		m_MS_LastTime		= timeGetTime();
	}
}



//------------------------------------------//
// Name : Tick                              //
// Desc : Return how many second had passed //
//------------------------------------------//
float CTimer::Tick()
{
	float delta_Time;
	if(m_IsPerfHardware)
	{
		QueryPerformanceCounter( &m_NS_CurrentTime );
		delta_Time = ( m_NS_CurrentTime.QuadPart - m_NS_LastTime.QuadPart ) / (float) m_NS_Frequency.QuadPart ;
	}
	else
	{
		m_MS_CurrentTime = timeGetTime();
		delta_Time		 = (float) (m_MS_CurrentTime - m_MS_LastTime) / 1000.0f;
	}
	return delta_Time;
}

//-----------------------------------------------------------------------//
// Name : FreshTime                                                      //
// Desc : use to set up the last time so we can check up for next render //
//-----------------------------------------------------------------------//
void CTimer::FreshTime()
{
	if(m_IsPerfHardware)
	{
		m_NS_LastTime = m_NS_CurrentTime;
	}
	else
	{
		m_MS_LastTime = m_MS_CurrentTime;
	}
	m_Count++;
	if(m_Count > g_FPS )
	{
		DWORD now		= timeGetTime();
		m_FPSAvarage	= 1000.0f / (float) ( ( now - m_LastFPSTime)/g_FPS );
		m_LastFPSTime	= now;
		m_Count			= 0;
	}
}

float CTimer::GetFrameRate()
{
	return m_FPSAvarage;
}